#!/bin/sh

if [ $# -ne 3 ]
then
	echo "usage: modifyHostname linux_type newhostname path"
	exit -1
fi
#flag: if linux type is error, flag = 1; else flag = 0
flag=0
newHostname=$2
path=$3
#oldHostname=""
echo $(pwd)
case "$1" in
	centos | redhat ) oldHostname=$(cat $path'/proc/sys/kernel/hostname')
					  echo $newHostname > $path'/proc/sys/kernel/hostname'
					  ;;
	debian | ubuntu ) oldHostname=$(cat $path'/etc/hostname')
					  echo $newHostname > $path'/etc/hostname'
					  ;;
	fedora          ) if  [ -f $path'/etc/sysconfig/network' ]
			  then 
			eval $(awk 'BEGIN{ FS="=";OFS="=";}\
								  $1=="HOSTNAME" \
								  { printf("oldHostname=%s\n",$2); $2="'$newHostname'";}\
								  { print $0 > "'$path'/etc/sysconfig/network"}'\
								   $path'/etc/sysconfig/network' )
			  else
				echo "HOSTNAME=$newHostname" > $path'/etc/sysconfig/network'
			  fi
		          ;;
	*               ) echo "Error"; flag=1;;
esac
if [ $flag -eq 1 ]
then
	echo "don't support $1 linux system"
	exit -2
fi

echo "oldHostname:$oldHostname"
#alter oldHostname in /etc/hosts file
rm -f $path'/etc/hosts.bk'
#if oldHostname be found in /etc/hosts, found = 1;else found =0
found=0
eval $(awk '{ found=0;i=0;\
		while ( i < NR ) \
		{ \
			if ( $i ~ /^'$oldHostname'$/) \
			{\
				$i = "'$newHostname'"; \
				found=1;\
			} \
			i++; \
		}\
		print $0 >> "'$path'/etc/hosts.bk";\
      } END{ printf("found=%d",found)}' $path'/etc/hosts')

echo "127.0.0.1 $newHostname"


rm -f $path'/etc/hosts'
mv $path'/etc/hosts.bk' $path'/etc/hosts'

#this part is opt
if [ $found -eq 0 ]
then
	echo "127.0.0.1 $newHostname" >> $path'/etc/hosts'
fi
#opt part end
echo "succeed to modify hostname:"
exit 0
